import { fromJS, toJS } from "immutable";

import {
    SET_CART_DATA,
    SET_LOADING,
    SET_CART_GOODS,
    MODIFY_CART_GOODS_CHECKED,
} from "./effects";

const initialState = fromJS({
    loading: true,
    data: [],
});

export default (state = initialState, action) => {
    switch (action.type) {
        case SET_CART_DATA:
            return state.set("data", fromJS(action.data));
        case SET_LOADING:
            return state.set("loading", action.value);
        case SET_CART_GOODS:
            //修改商品的数量或者是选中的状态
            const { type, id, ...rest } = action;
            const index = state
                .get("data")
                .findIndex((item) => item.get("_id") === id);
            let newState = null;
            Object.entries(rest).forEach(([key, value]) => {
                newState = state.setIn(["data", index, key], value);
            });
            return newState;
        case MODIFY_CART_GOODS_CHECKED:
            return state.set("data", fromJS(action.data));
        default:
            return state;
    }
};
